package com.atguigu.springcloud.controller;


import com.atguigu.springcloud.service.PaymentHystrixService;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
//@DefaultProperties(defaultFallback = "com.atguigu.springcloud.fallback.GlobalMethod.globalFallbackMethod" )
public class OrderHystrixController {

    @Autowired
    private PaymentHystrixService paymentHystrixService;

    @GetMapping("/consumer/payment/hystrix/ok/{id}")
    public String paymentOk(@PathVariable String id){
        return paymentHystrixService.paymentOk(id);
    }


    @HystrixCommand(fallbackMethod = "paymentInfoHanlder",
                   commandProperties = {
            // 在10个请求内，10s内，如果出错率达到60%
                        @HystrixProperty(name="circuitBreaker.enabled",value = "true"),
                        @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),
                        @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),
                        @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60")
                                        }
                   )
    /*@HystrixCommand(fallbackMethod = "paymentInfoHanlder",
            commandProperties = { //数组设置超时
                    @HystrixProperty(name =  "execution.isolation.thread.timeoutInMilliseconds",value = "2000"),

            }
    )*/
    @GetMapping("/consumer/payment/hystrix/timeout/{id}")
//    @HystrixCommand
    public String paymentTimeout(@PathVariable String id){
//        int i = 1 /0;
//        return paymentHystrixService.paymentTimeout(id);
        if (Integer.valueOf(id) < 0) {
            throw new RuntimeException("报错了");
        }
        return "正常";
    }

    //自动调用fallback中的方法
    public String paymentInfoHanlder(String id){
        return "客户端：：：：系统繁忙:线程池   "+Thread.currentThread().getName() +" payment_timeOut, id:  "+id+"   fallback:  enter falback";
    }
}
